/**
 * Date :
 * BTime:
 * ETime:
 * Title:
 * Address:
 */

#include <iostream>
#include <vector>
#include <list>
#include <string>

using namespace std;

int main() {
	int qq;
	cin >> qq;
	vector<list<int>> dq(10);
	
	for (int i = 0; i < qq; ++i) {
		string op;
		cin >> op;
		if (op == "push_back" || op == "pop_back") {
			int a, x;
			cin >> a >> x;
			if (op == "push_back") {
				dq[a - 1].push_back(x);
			} else {
				if (!dq[a - 1].empty()) {
					dq[a - 1].pop_back();
				}
			}
		} else if (op == "push_front" || op == "pop_front") {
			int a, x;
			cin >> a >> x;
			if (op == "push_front") {
				dq[a - 1].push_front(x);
			} else {
				if (!dq[a - 1].empty()) {
					dq[a - 1].pop_front();
				}
			}
		} else if (op == "size") {
			int a;
			cin >> a;
			cout << dq[a - 1].size() << endl;
		} else if (op == "front") {
			int a;
			cin >> a;
			if (!dq[a - 1].empty()) {
				cout << dq[a - 1].front() << endl;
			}
		} else if (op == "back") {
			int a;
			cin >> a;
			if (!dq[a - 1].empty()) {
				cout << dq[a - 1].back() << endl;
			}
		}
	}
	
	return 0;
}

